import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { LeftOutline, MoreOutline } from 'antd-mobile-icons';
import { Popover } from 'antd-mobile';
import { bem, commonUtils } from '@/utils';
import classNames from 'classnames';
import { useNavigate } from 'react-router-dom';

export interface SwiperNavProps {
    menuList: [
        {
            title?: string;
            navShow?: boolean;
        }
    ];
    activeTab?: number;
    bannerHeight?: number;
    scrollNavShow?: boolean;
    navMoreContent?: React.ReactNode;
    headerFadeRadio?: {
        start: number;
        end: number;
    };
    onHandlerActive?: (index: number) => void;
}

const defaultProps = {
    bannerHeight: 375,
    scrollNavShow: false,
    headerFadeRadio: {
        start: .65,
        end: .78
    },
}

const SwiperNav: React.FC<SwiperNavProps> = (props) => {
    const {
        menuList,
        activeTab,
        navMoreContent,
        onHandlerActive,
        bannerHeight,
        headerFadeRadio,
        scrollNavShow,
        ...rest
    } = {
        ...defaultProps,
        ...props
    };

    const b = bem('swiper');
    const scrollLock = useRef(false);
    const [opacityState, setOpacityState] = useState(0);
    const [headerClass, setHeaderClass] = useState(() => {
        return scrollNavShow ? b('nav-op') : '';
    });
    const [showMoreNav, setShowMoreNav] = useState(false);
    const navigate = useNavigate();

    const doLockFun = (func: () => void) => {
        if (scrollLock.current) {
            return;
        }
        scrollLock.current = true;

        func?.();

        requestAnimationFrame(() => {
            scrollLock.current = false;
        });
    }

    const handlerActive = (index: number) => {
        doLockFun(() => {
            onHandlerActive?.(index);
        });
    }

    /**
     * 是否展示tab
     */
    const getTabShow = useCallback((isShow?: boolean) => {
        if (isShow == null) return {};
        return isShow ? {} : { display: 'none' };
    }, []);

    /**
     * Back
     */
    const handleBack = () => {
        navigate(-1);
    };


    const handleScroll = () => {
        if (!scrollNavShow) {
            return;
        }
        doLockFun(() => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            const opacityRadio = commonUtils.calScrollHeaderRadio(scrollTop, bannerHeight, headerFadeRadio);

            setShowMoreNav(false);
            if (opacityRadio == 1) {
                setHeaderClass('');
            } else {
                setHeaderClass(b('nav-op'));
            }
            if (opacityState != 1) {
                // 只在透明度变化明显时更新
                setOpacityState(opacityRadio);
            }

        });
    };

    const handlerClickMore = useCallback(() => {
        setShowMoreNav(!showMoreNav);
    }, [showMoreNav]);

    useEffect(() => {
        if (!scrollNavShow) {
            return;
        }
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);

    const menuItems = useMemo(() => {
        return menuList.map((item, index) => {
            const { title, navShow } = item;
            const isActive = activeTab === index;

            return (
                <div
                    key={index}
                    className={classNames(
                        b('nav-tab__item'),
                        isActive && b('nav-tab__item-active')
                    )}
                    style={getTabShow(navShow)}
                    onClick={() => handlerActive(index)}
                >
                    <div className={b('nav-tab__item__title')}>
                        {title}
                    </div>
                </div>
            );
        });
    }, [menuList, activeTab, getTabShow, handlerActive]);


    return (
        <div className={classNames(b('nav'), headerClass)} >
            <div className={classNames(b('nav-btn'), b('back'))} onClick={handleBack}><LeftOutline /></div>
            <div className={b('nav-tab')} style={{ opacity: opacityState }}>
                {menuItems}
            </div>

            <Popover key={'moreOutLine'} mode='dark' content={navMoreContent} visible={showMoreNav} >
                <div className={classNames(b('nav-btn'))} onClick={handlerClickMore}>
                    <MoreOutline />
                </div>
            </Popover>

        </div>
    )
};

export default SwiperNav;